package com.study.leetcode;

public class Solution_63 {
    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
        int rows = obstacleGrid.length;
        int cols = obstacleGrid[0].length;
        if (obstacleGrid[0][0] == 1 || obstacleGrid[rows - 1][cols - 1] == 1) {
            return 0;
        }
        obstacleGrid[0][0] = -1;
        for (int j = 1; j < cols; j++) {
            if (obstacleGrid[0][j] == 0) {
                obstacleGrid[0][j] = obstacleGrid[0][j - 1];
            } else {
                break;
            }
        }
        for (int j = 1; j < rows; j++) {
            if (obstacleGrid[j][0] == 0) {
                obstacleGrid[j][0] = obstacleGrid[j - 1][0];
            } else {
                break;
            }
        }
        for (int i = 1; i < rows; i++) {
            for (int j = 1; j < cols; j++) {
                if (obstacleGrid[i][j] == 1) {
                    continue;
                }
                if (obstacleGrid[i - 1][j] != 1) {
                    obstacleGrid[i][j] += obstacleGrid[i - 1][j];
                }
                if (obstacleGrid[i][j - 1] != 1) {
                    obstacleGrid[i][j] += obstacleGrid[i][j - 1];
                }
            }
        }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.printf("%-4d,",obstacleGrid[i][j]);
            }
            System.out.println();
        }
        return -obstacleGrid[rows - 1][cols - 1];
    }

    public static void main(String[] args) {
        int map[][] = {
                {0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0},
                {0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1},
                {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0},
                {0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0},
                {0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0},
                {0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0},
                {0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0},
                {0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0},
        };
        int roads = uniquePathsWithObstacles(map);
        System.out.println(roads);
    }
}
